package com.sjz.han.industry.wxapi;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;


import com.sjz.han.industry.MainActivity;
import com.sjz.han.industry.R;
import com.sjz.han.industry.activites.LoginActivity;
import com.sjz.han.industry.activites.PayActivity;
import com.sjz.han.industry.base.AppConfig;
import com.sjz.han.industry.entities.LoignEntity;
import com.sjz.han.industry.internetmanage.ReqestUrl;
import com.sjz.han.industry.utils.JsonUtils;
import com.sjz.han.industry.utils.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.ResponseBody;


public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private static final String TAG = "MicroMsg.SDKSample.WXPayEntryActivity";

    private IWXAPI api;
    private TextView tvTitle;
    private ImageView ivShow;
    private RelativeLayout rlReturn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.pay_result);
        this.getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);
        api = WXAPIFactory.createWXAPI(this, WeiXinPayMethod.APP_ID);
        api.handleIntent(getIntent(), this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {


    }

    @Override
    public void onResp(BaseResp resp) {
        Log.i("WXPAY","FANHUICODE==="+resp.getType());
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    SendAuth.Resp sendResp = (SendAuth.Resp) resp;
                    if (sendResp != null) {
                        String code = String.valueOf(sendResp.code);
                        getAccess_token(code);
                    }

                    finish();
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:

                    finish();
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:

                    finish();
                    break;
                default:
                    finish();
                    break;
            }
        } else if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            ToastUtils.popUpToast("是否成功==="+resp.errCode);
            if (resp.errCode == 0) {
                startActivity(new Intent(this,MainActivity.class));
                ToastUtils.popUpToast("充值成功，恭喜");
            } else {
                ToastUtils.popUpToast("充值失败，请稍后再试");
            }
            autoFinish();
        } else if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) {
            finish();
        }
    }

//		if(resp.getType()== ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX){//分享
//			Log.i("ansen","微信分享操作.....");
//			WeiXin weiXin=new WeiXin(2,resp.errCode,"");
//			EventBus.getDefault().post(weiXin);	}


    private void autoFinish() {
        finish();
    }

    /**
     * 获取openid accessToken值用于后期操作
     *
     * @param code 请求码
     */
    private void getAccess_token(final String code) {
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + AppConfig.app_id
                + "&secret="
                + AppConfig.AppSecret
                + "&code="
                + code
                + "&grant_type=authorization_code";
        OkHttpUtils
                .get()
                .url(path)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        String openid = jsonObject.getString("openid").trim();
                        String access_token = jsonObject.getString("access_token").trim();
                        getUserMesg(access_token, openid);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });



    }

    /**
     * 获取微信的个人信息
     *
     * @param access_token
     * @param openid
     */
    private void getUserMesg(final String access_token, final String openid) {
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + access_token
                + "&openid="
                + openid;
        Log.i("wexin", "getUserMesg：" + path);

        OkHttpUtils
                .get()
                .url(path)
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtils.popUpToast("请求超时");
            }
            @Override
            public void onResponse(String response, int id) {
                if(ReqestUrl.rebacRequestJson(response)!=null){
                    JSONObject jsonObject = null;
                    try {
                        try {
                            jsonObject = new JSONObject(response);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        String nickname = jsonObject.getString("nickname");
                        int sex = Integer.parseInt(jsonObject.get("sex").toString());
                        String headimgurl = jsonObject.getString("headimgurl");

                        Log.i("wexin", "用户基本信息:" + jsonObject.toString());
                        Log.i("wexin", "nickname:" + nickname);
                        Log.i("wexin", "sex:" + sex);
                        Log.i("wexin", "headimgurl:" + headimgurl);
//                        wexinLogin(openid, nickname, headimgurl);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    finish();
                }
            }
        });

    }

}